package com.lmscn.lms.api.model;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * Created by Czl on 2015/7/24.
 */
@SuppressWarnings("serial")
public class CourseBase extends Model<CourseBase> {
	
	

//	@Override
//	public boolean equals(Object o) {
//		final CourseBase c = (CourseBase)o;  
//        if(this.get("id").equals(c.get("id"))){  
//            return true;  
//        } 
//        return false;
//	}

	public static final CourseBase dao = new CourseBase();

	/**
	 * 根据课程编号获取相应课程；
	 * 
	 * @author zhang.xx
	 * @date 2016年12月6日13:35:45
	 * @param courseNo
	 * @return
	 */
	public CourseBase findByCourseNo(String courseNo) {

		String sql = "select * from t_course_base t where t.course_no = ? ";

		return dao.findFirst(sql, courseNo);
	}

	
	/**
	 * 获取关联列表
	 * 
	 * @param courseCategoryId
	 * @return
	 */
	public Page<CourseBase> getPageCoursesByCategory(String searchText, String categoryIds,
			String courseIds, boolean ignoreSelected, Long studentId, int pageNumber, int pageSize) {
		String sql = " from t_course_base c, t_course_learning_setting s"
				+ " where c.is_display = 1 and c.id = s.course_id and c.id not in ("+ courseIds +") ";
		if (ignoreSelected && studentId!=null) {
			sql += " and not exists (select cs from t_course_student cs"
					+ " where cs.course_id = c.id and cs.student_id = "
					+ studentId + ")";
		}
		if (categoryIds!=null && !"".equals(categoryIds.trim())) {
			sql += " and c.category_id in (" + categoryIds + ")";
		}
		if (searchText!=null && !"".equals(searchText.trim())) {
			sql += " and (c.name like '%"+ searchText +"%' or c.teacher_name like '%"+ searchText +"%')";
		} else {
			sql += " and s.type = 0";
		}
		sql += " order by c.id desc";
		
		return dao.paginate(pageNumber, pageSize, "select c.* ", sql);
		
//		return dao.paginate(pageNumber, pageSize, "select t.* ",
//		" from t_course_category_related t where t.category_id = ? order by seq desc ", courseCategoryId);
	}



	/**
	 * 一对一获取课件
	 * 
	 * @return
	 */
	public CourseLesson getCourseLesson() {
		return CourseLesson.dao.findByCourseId(Long.parseLong(get("id").toString()));
	}

	/**
	 * 一对一获取课时
	 * 
	 * @return
	 */
	public CourseLearningSetting getCourseLearningSetting() {
		return CourseLearningSetting.dao.findByCourseId(Long.parseLong(get("id").toString()));
	}

	/**
	 * 一对多获取课程相关评论
	 * 
	 * @return
	 */
	public List<Comment> getCourseCommentList() {
		return Comment.dao.findByCourseId(Long.parseLong(get("id").toString()));
	}

	/**
	 * 查询相关课程
	 * 
	 * @return
	 */
	public List<CourseBase> getAboutCourses(Long courseId) {
		CourseBase courseBase = CourseBase.dao.findById(courseId);
		String tags = courseBase.getStr("tags").substring(1, courseBase.getStr("tags").length());
		String[] tagArr = tags.split("&");
		List<CourseBase> courseBaseList = new ArrayList<CourseBase>();
		for (String tag : tagArr) {
			List<CourseBase> courseBases = CourseBase.dao.findByTags(tag, courseId);
			for (CourseBase coursebase : courseBases) {
				// 判断已经存在的不进行add
				if (!courseBaseList.contains(coursebase)) {
					courseBaseList.add(coursebase);
				}
			}
			// 限制为只查询12条
			if (courseBaseList.size() > 12) {
				courseBaseList = courseBaseList.subList(0, 12);
				break;
			}
		}
		// return new ArrayList<CourseBase>(new LinkedHashSet<CourseBase>(courseBaseList));
		return courseBaseList;
	}

	public List<CourseBase> getAboutCourses(Long courseId, int pageNumber, int pageSize) {
		CourseBase courseBase = CourseBase.dao.findById(courseId);
		String tags = courseBase.getStr("tags").substring(1, courseBase.getStr("tags").length());
		String[] tagArr = tags.split("&");
		List<CourseBase> courseBaseList = new ArrayList<CourseBase>();
		for (String tag : tagArr) {
			List<CourseBase> courseBases = CourseBase.dao.findByTags(tag, courseId, pageNumber, pageSize);
			for (CourseBase coursebase : courseBases) {
				courseBaseList.add(coursebase);
			}
		}
		return new ArrayList<CourseBase>(new LinkedHashSet<CourseBase>(courseBaseList));
	}

	/**
	 * 关键词查询课程
	 * 
	 * @param queryString
	 * @return
	 */
	public List<CourseBase> getLikeQueryString(String queryString) {
		return dao.find("select * from t_course_base where name like ? or teacher_name like ? ", "%" + queryString + "%", "%"
				+ queryString + "%");
	}

	/**
	 * 分页根据关键词查询课程
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @param paras
	 * @return
	 */
	public Page<CourseBase> getPageLikeQueryString(int pageNumber, int pageSize, String sql, Object[] paras) {
		return dao.paginate(pageNumber, pageSize, "select t.* ", sql, paras);
	}

	/**
	 * 分页查询课程
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @param sql
	 * @param paras
	 * @return
	 */
	public Page<CourseBase> findCoursePage(int pageNumber, int pageSize, String sql, Object[] paras) {
		return dao.paginate(pageNumber, pageSize, "select t.* ", sql, paras);
	}
	
	/**
	 * 获取选课人数
	 * 
	 * @return
	 */
	public Long getCount(Long courseId) {
		return Db.queryLong("select count(id) from t_course_student where course_id =? ", courseId);
	}

	/**
	 * 获取分类下课程数量
	 * 
	 * @param courseCategoryId
	 * @return
	 */
	public long getCourseCount(Long courseCategoryId) {
		return Db.queryLong("select count(id) from t_course_base where category_id = ?", courseCategoryId);
	}

	public Long getAllCount() {
		return Db.queryLong("select count(t.id) from t_course_base t ");
	}

	/**
	 * 获取分类下课程列表
	 * 
	 * @param courseCategoryId
	 * @return
	 */
	public Page<CourseBase> getByCategoryId(Long courseCategoryId, int pageNumber, int pageSize) {
		return dao.paginate(pageNumber, pageSize, "select t.* "," from t_course_base t where t.category_id = ? order by create_time desc ", courseCategoryId);
	}
	/**
	 * 分页获取按指定排序规则排序后的课程
	 * @param pageNumber
	 * @param pageSize
	 * @param orderBy
	 * @return
	 */
	public Page<CourseBase> getCoursePage(int pageNumber, int pageSize,String orderBy){
		return dao.paginate(pageNumber, pageSize, "select t.* ", "from t_course_base t order by " + orderBy);
	}
	/**
	 * 获取随机推荐课程
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	public Page<CourseBase> getRandomCourses(int pageNumber, int pageSize, int level) {
		String sqlString = " from t_course_base t where t.level <= ? order by rand() ";
		System.out.println(sqlString);
		return dao.paginate(pageNumber, pageSize, "select t.* ", sqlString, level);
	}

	/**
	 * 查询推荐课程
	 * 
	 * @param courseStudentClicks
	 * @return
	 */
	public Page<CourseBase> getRelatedCourses(List<CourseStudentClick> courseStudentClicks, int pageNumber, int pageSize) {
		Page<CourseBase> courseBasePage = null;
		List<CourseBase> courseBaseList = new ArrayList<CourseBase>();

		for (CourseStudentClick studentClick : courseStudentClicks) {
			CourseBase courseBase = CourseBase.dao.findById(studentClick.getLong("course_id"));
			List<CourseBase> courseBases = getAboutCourses(courseBase.getLong("id"));
			for (CourseBase courseBase1 : courseBases) {
				courseBaseList.add(courseBase1);
			}
		}

		List<CourseBase> noRepeatList = new ArrayList<CourseBase>(new LinkedHashSet<CourseBase>(courseBaseList));
		int totalPage = (noRepeatList.size() - 1) / pageSize + 1;

		List<CourseBase> pageList = getPageList(noRepeatList, pageNumber, pageSize, totalPage);
		courseBasePage = new Page<CourseBase>(pageList, pageNumber, pageSize, totalPage, noRepeatList.size());
		return courseBasePage;
	}

	public static List getPageList(List list, int currentPage, int maxNum, int pageNum) {
		int fromIndex = 0; // 从哪里开始截取
		int toIndex = 0; // 截取几个
		if (list == null || list.size() == 0)
			return null;
		// 当前页小于或等于总页数时执行
		if (currentPage <= pageNum && currentPage != 0) {
			fromIndex = (currentPage - 1) * maxNum;
			if (currentPage == pageNum) {
				toIndex = list.size();
			} else {
				toIndex = currentPage * maxNum;
			}
		}
		return list.subList(fromIndex, toIndex);
	}

	public Page<CourseBase> getLikeString(String tag, int pageNumber, int pageSize) {
		return dao.paginate(pageNumber, pageSize, "select t.* ", " from t_course_base t where t.tags contains(?)", tag);
	}

	/**
	 * 查询标签课程
	 * 
	 * @param tags
	 * @return
	 */
	public List<CourseBase> findByTags(String tags, Long courseId) {
		return dao.find("select t.* from t_course_base t where t.tags like ? and t.id !=?", "%" + tags.trim() + "%", courseId);
	}

	public List<CourseBase> findByTags(String tags, Long courseId, int pageNumber, int pageSize) {
		return dao.find("select t.* from t_course_base t where t.tags like ? and t.id !=? limit ?,? ", "%" + tags.trim() + "%",
				courseId, (pageNumber - 1) * pageSize, pageNumber * pageSize);
	}

	/**
	 * 查询指定教师所主讲的课程
	 * @param teacherIds
	 * @return
	 */
	public List<CourseBase> findByTeacher(String teacherIds){
		return dao.find("select t.* from t_course_base t where t.teacher_ids = ?",teacherIds);
	}
	/**
	 * 获取首页猜你喜欢课程
	 * 
	 * @return
	 */
	public List<CourseBase> getGeussLikeCoursesBases() {

		// String sql =
		// "SELECT * FROM t_course_base t ORDER BY t.record_time DESC LIMIT 4 ";

		// 数据根据用户点赞、收藏、已学完课程综合推荐相关课程
		// 已学完课程條件未添加
		// String sql = "select t.* from t_course_base t " +
		// // 使用了一个随机取值
		// " order by t.ckgood_num DESC,t.collection_num DESC,RAND() " +
		// " limit 4 ";

		String sql = "select t.* from t_course_base t order by rand() limit 4 ";

		return dao.find(sql);
	}

	/**
	 * 猜你喜欢二级页面
	 * 
	 * @date 2016年11月14日13:48:18
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	public Page<CourseBase> getGuessLikeCoursesPage(int pageNumber, int pageSize) {
		String sql = " from t_course_base t order by t.ckgood_num DESC,t.collection_num DESC ";
		return dao.paginate(pageNumber, pageSize, "select t.* ", sql);
	}
	public Page<CourseBase> getRichCoursesPage(int pageNumber, int pageSize) {
		String sql = "FROM t_course_base t,t_course_lesson s where t.id = s.course_id " +
				"and s.assemble_type = 4 ORDER BY t.is_top DESC,t.record_time DESC ";
		return dao.paginate(pageNumber, pageSize, "select t.* ", sql);
	}

	/**
	 * 获取4门精品微课
	 * 
	 * @date 2016年11月13日11:19:29
	 * @return
	 */
	public List<CourseBase> getFourCompetitiveCourses() {

		// 添加置顶的排序 2017年2月16日13:13:39
//		String sql = "SELECT * FROM t_course_base t ORDER BY t.is_top DESC,t.record_time DESC LIMIT 4 ";
		// 去除富媒体课程的显示
		String sql = "SELECT t.* FROM t_course_base t, t_course_lesson s where t.id = s.course_id " +
				"and (s.assemble_type is null or s.assemble_type <> 4) ORDER BY s.viewed_num DESC LIMIT 4 ";

		return dao.find(sql);
	}
	public List<CourseBase> getFourRichCourses() {
		
		// 添加置顶的排序 2017年2月16日13:13:39
		// 
		String sql = "SELECT t.* FROM t_course_base t,t_course_lesson s where t.id = s.course_id " +
				"and s.assemble_type = 4 ORDER BY t.play_num DESC,t.record_time DESC LIMIT 4 ";
		
		return dao.find(sql);
	}

	/**
	 * 特别推送模拟数据
	 * 
	 * @date 2016年11月13日16:39:42
	 * @return
	 */
	public List<CourseBase> getFourSpecialPushCourses() {

		String sql = "SELECT * FROM t_course_base t ORDER BY t.record_time DESC LIMIT 4 ";

		return dao.find(sql);
	}

	/**
	 * 获取相关微课
	 * 
	 * @date 2016年11月16日16:51:52
	 * @param keyWord
	 * @return
	 */
	public List<CourseBase> getFourAboutCourses(String keyWord) {
		String sql = "SELECT t.* FROM t_course_base t WHERE t.tags like '%" + keyWord + "%' " + "limit 12 ";
		return dao.find(sql);
	}
	
	
	/**
	 * 学员最近学习的课程
	 * @param studentId
	 * @param limit
	 * @return
	 */
	public List<CourseBase> findLastLearnedCourseList(long studentId, int limit) {
		String sql = "select c.* from t_course_base c, t_course_student cs"
				+ " where cs.course_id = c.id and cs.student_id = ? order by cs.id desc limit 0, ?";
		return dao.find(sql, studentId, limit);
	}

}
